﻿using DataConvertLib;
using PLC.Interface.Groups;
using PLC.Interface.Variables;
using PLCWpfTest.Common;
using PLCWpfTest.Models;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using YWM.Common.Exceptions;
using YWM.Dto;

namespace PLCWpfTest.ViewModels
{
    public class VariableOperationViewModel : OperationViewModel
    {
        public NameValueModel<byte>[] DataTypes { get; set; }

        private readonly IVariableAppService _variableAppService;

        private readonly IGroupAppService _groupAppService;

        private IReadOnlyList<GroupResultDto> _groups;
        public IReadOnlyList<GroupResultDto> Groups
        {
            get { return _groups; }
            set { SetProperty(ref _groups, value); }
        }

        public VariableDto Variable { get; set; } = new VariableDto();

        public VariableOperationViewModel(IVariableAppService variableAppService, IGroupAppService groupAppService, VariableDto variable)
        {
            string[] names = Enum.GetNames(typeof(DataType));
            DataTypes = new NameValueModel<byte>[names.Length];
            for (byte i = 0; i < names.Length; i++)
            {
                DataTypes[i] = new NameValueModel<byte>(names[i], i);
            }

            _variableAppService = variableAppService;
            _groupAppService = groupAppService;

            if (variable != null)
            {
                Variable = variable;
                IsAdd = false;
            }
        }

        protected override async Task LoadCommand_Executing(object parameter)
        {
            IReadOnlyList<GroupResultDto> groups = await _groupAppService.GetList(false);
            Groups = groups;
        }

        protected override bool OkCommand_BeforeCanExecute(object parameter)
        {
            return Variable.IsValidated;
        }

        protected override async Task<IEntityDto> OkAsync(object parameter)
        {
            Variable.Error = string.Empty;
            VariableDto variable = await _variableAppService.Save(Variable);
            CommunicationCache.Groups = await _groupAppService.GetList(true);
            RaiseRequestClose();
            return variable;
        }

        protected override void OkCommand_UnexecutedFriendlyException(FriendlyException ex)
        {
            Variable.Error = ex.Message;
        }
    }
}
